/**
 * Created by Administrator on 2017/5/11.
 */
var roleType = sessionStorage.getItem("roleType");//从缓存拿角色的参数
if(roleType=='3'){
    $(".event-content").hide();
    $('#myModal').modal('show');
    setTimeout(function(){
        $("#myModal").modal("hide")
    },1200);
}else{
    $(".event-content").show();
}
    var map = new BMap.Map("map");  // 创建Map实例
    var point = new BMap.Point(119.014521, 25.459865);// 初始化地图,用城市名设置地图中心点
    map.centerAndZoom(point, 14);//
    map.enableScrollWheelZoom();//地图可以缩放
    map.enableContinuousZoom();

    var blist = [];
    var districtLoading = 0;

    function getBoundary() {
        addDistrict("莆田市");
    }

    /**
     * 添加行政区划
     * @param {} districtName 行政区划名
     * @returns  无返回值
     */
    function addDistrict(districtName) {
        //使用计数器来控制加载过程
        districtLoading++;
        var bdary = new BMap.Boundary();
        bdary.get(districtName, function (rs) {       //获取行政区域
            var count = rs.boundaries.length; //行政区域的点有多少个
            if (count === 0) {
                alert('未能获取当前输入行政区域');
                return;
            }
            for (var i = 0; i < count; i++) {
                blist.push({points: rs.boundaries[i], name: districtName});
            }
            ;
            //加载完成区域点后计数器-1
            districtLoading--;
            if (districtLoading == 0) {
                //全加载完成后画端点
                drawBoundary();
            }
        });
    }

    function drawBoundary() {
        //包含所有区域的点数组
        var pointArray = [];
        var pNW = {lat: 59.0, lng: 73.0};
        var pNE = {lat: 59.0, lng: 136.0};
        var pSE = {lat: 3.0, lng: 136.0};
        var pSW = {lat: 3.0, lng: 73.0};
        var pArray = [];
        pArray.push(pNW);
        pArray.push(pSW);
        pArray.push(pSE);
        pArray.push(pNE);
        pArray.push(pNW);
        //循环添加各闭合区域
        for (var i = 0; i < blist.length; i++) {
            //添加显示用标签层
            var label = new BMap.Label(blist[i].name, {offset: new BMap.Size(20, -10)});
            label.hide();
            map.addOverlay(label);

            //添加多边形层并显示
            var ply = new BMap.Polygon(blist[i].points, {
                strokeWeight: 1,
                strokeColor: "#FF0000",
                fillOpacity: 0.01,
                fillColor: " #FFFFFF"
            }); //建立多边形覆盖物
            ply.name = blist[i].name;
            ply.label = label;
            map.addOverlay(ply);


            //将点增加到视野范围内
            var path = ply.getPath();
            pointArray = pointArray.concat(path);
            //将闭合区域加到遮蔽层上，每次添加完后要再加一次西北角作为下次添加的起点和最后一次的终点
            pArray = pArray.concat(path);
            pArray.push(pArray[0]);
        }

        // //限定显示区域，需要引用api库
        // var boundply = new BMap.Polygon(pointArray);
        // BMapLib.AreaRestriction.setBounds(map, boundply.getBounds());
        // map.setViewport(pointArray);    //调整视野
        //添加遮蔽层
        var plyall = new BMap.Polygon(pArray, {
            strokeOpacity: 0.0000001,
            strokeColor: "#000000",
            strokeWeight: 0.00001,
            fillColor: "#000000",
            fillOpacity: 0.6
        }); //建立多边形覆盖物
        map.addOverlay(plyall);
    }

    getBoundary();
//声明两个对象用来缓存marker和eventWindow，使用id来查询和添加缓存
    var cacheMap = null;
    var infoWindowMap = null;

    /**
     * 自定义map
     * @constructor
     */
    function Map() {

        var mapObj = {};

        this.put = function (key, value) {
            mapObj[key] = value;
        };

        this.remove = function (key) {
            if (mapObj.hasOwnProperty(key)) {
                delete mapObj[key];
            }
        };

        this.get = function (key) {
            if (mapObj.hasOwnProperty(key)) {
                return mapObj[key];
            }
            return null;
        };

        this.getKeys = function () {
            var keys = [];
            for (var k in mapObj) {
                keys.push(k);
            }
            return keys;
        };

        // 遍历map
        this.each = function (fn) {
            for (var key in mapObj) {
                fn(key, mapObj[key]);
            }
        };

        this.toString = function () {
            var str = "{";
            for (var k in mapObj) {
                str += "\"" + k + "\" : \"" + mapObj[k] + "\",";
            }
            str = str.substring(0, str.length - 1);
            str += "}";
            return str;
        }

    }


    /**查询全部在百度地图上事件**/
    function queryEvent() {
        $.ajax({
            type: "GET",
            url: "/rest/web/eventInfo/selectEventInfoList",
            dataType: "json",
            success: function (data) {
                //每次查询后都把marker和eventWindow缓存的数据清空掉
                cacheMap = new Map();
                infoWindowMap = new Map();
                var eventList = data.data;
                $.each(eventList, function (i, o) {
                    setEventPoint(o);
                });
                //查询列表
                var reportEventHtml = "";
                var statusTotal = 0;//声明未处理的总数
                $.each(eventList, function (i, n) {
                    //查询未处理的次数
                    if (n.status == "0") {
                        statusTotal = statusTotal + 1;
                    }
                    var status = (n.status == "0" ? "未处理" : "已完成");
                    if (i == 0) {
                        getSingleEvent(n.id);
                        reportEventHtml = reportEventHtml + "<li data-id='" + n.id + "'> <p>" + n.createTime + "</p> <p>" + status + "</p> <p>" + n.title + "</p></li>";
                    }
                    else {
                        reportEventHtml = reportEventHtml + "<li data-id='" + n.id + "'> <p>" + n.createTime + "</p> <p>" + status + "</p><p>" + n.title + "</p></li>";
                    }
                });
                $("#reportEvent").html(reportEventHtml);
                $("#reportEvent>li").click(function () {
                    getSingleEvent($(this).attr("data-id"));
                });
                //求出总数的方法
                var data = data.data;
                var dealWith = "";
                dealWith += "<div><p class='statusTotal'>未处理：<span>" + statusTotal + "</span></p><p>/总数：<span>" + data.length + "</span></p></div>";
                $(".dealWith-div").html(dealWith);
            }
        });
    }

    /**
     * 绘制点事件
     * @param obj
     */
    function setEventPoint(obj) {
        var eventContent = "";
        eventContent = eventContent + "<div class='event ' id='senseDemo'>" +
            "<div class='header'><h3>事件上报&nbsp;&nbsp;&nbsp;" + obj.id + "</h3></div>" +
            "<div class='content'>" +
            "<div class='user-message'><img src='" + obj.userIcon + "'><div><h1>" + obj.nickName + "</h1><h5>" + obj.department + "</h5></div></div>" +
            "<div class='details'><h6>主题：</h6><p>" + obj.title + "</p></div>" +
            "<div class='details details-content'><h6>内容：</h6><p>" + obj.content + "</p></div>" +
            "<div class='details '><h6>时间：</h6><p>" + obj.createTime + "</p></div>" +
            "<div class='details details-address'><h6>地址：</h6><p>" + obj.address + "</p></div>" +
            "<div class='classify'>" +
            "<div><h6>坐标：</h6><p class='coordinate'>" + obj.lng + "," + obj.lat + "</p></div></div>" +
            "<div class='details-images'><h6>图片：</h6>" +
            "<ul class='images'>";
        if (obj.pic != null) {
            var imgArr = obj.pic.split(",");
            for (var j = 0; j < imgArr.length; j++) {
                eventContent = eventContent + "<li><img src='" + imgArr[j] + "' class='imgBtn'></li>";
            }
        }
        eventContent = eventContent + "</ul></div></div></div></div></div>";
        var eventWindow = new BMap.InfoWindow(eventContent); // 创建信息窗口对象

        //创建事件小图标
        var pt = new BMap.Point(obj.lng, obj.lat);
        var myIcon = new BMap.Icon("/static/images/map_event.png", new BMap.Size(22, 22));
        var marker = new BMap.Marker(pt, {icon: myIcon}); // 创建标注
        map.addOverlay(marker);
        marker.addEventListener("click", function () {
            this.openInfoWindow(eventWindow);
            $('.images').viewer();
        });
        //将marker和eventWindow缓存起来
        cacheMap.put(obj.id, marker);
        infoWindowMap.put(obj.id, eventWindow);
    }

    /**
     * 根据id把缓存的marker和eventWindow拼装后调用map的openInfoWindow方法弹窗展示
     * @param id
     */

    function getSingleEvent(id) {
        var infoWindow = infoWindowMap.get(id);
        var marker = cacheMap.get(id);
        marker.openInfoWindow(infoWindow);
        $('.images').viewer();
    }

    queryEvent();
    /**搜索框的模糊查询**/
    $("#blurBtn").click(function () {
        var title = $("#title").val();
        $.ajax({
            type: "GET",
            url: "/rest/web/eventInfo/selectEventInfoList",
            dataType: "json",
            data: {title: title},
            success: function (data) {
                var eventList = data.data;
                var reportEventHtml = "";
                $.each(eventList, function (i, n) {
                    //对未处理与已处理进行判断
                    var status = (n.status == "0" ? "未处理" : "已完成");
                    if (i == 0) {
                        getSingleEvent(n.id);
                        reportEventHtml = reportEventHtml + "<li data-id='" + n.id + "'> <p>" + n.createTime + "</p> <p>" + status + "</p> <p>" + n.title + "</p></li>";
                    }
                    else {
                        reportEventHtml = reportEventHtml + "<li data-id='" + n.id + "'> <p>" + n.createTime + "</p> <p>" + status + "</p><p>" + n.title + "</p></li>";
                    }
                });
                $("#reportEvent").html(reportEventHtml);
                $("#reportEvent>li").click(function () {
                    getSingleEvent($(this).attr("data-id"));
                });
            }
        });
    });



